#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 8080
#define SERVER_IP "127.0.0.1"
#define BUFFER_SIZE 1024

int main()
{
    int fd = 0;
    int ret = 0;
    unsigned int len = 0;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE] = "connect";

    // 创建socket文件描述符
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        std::cerr << "Could not create socket" << std::endl;
        return 1;
    }

    memset(&server_addr, 0, sizeof(server_addr));

    // 填充服务器信息
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);

    // 将IPv4地址从文本转换成二进制形式
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        return 1;
    }

    if (sendto(fd, (const char*)buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "Send failed" << std::endl;
        return 1;
    }

    // 接收服务器回传的数据
    len = sizeof(server_addr);
    ret = recvfrom(fd, (char*)buffer, BUFFER_SIZE, MSG_WAITALL, (struct sockaddr*)&server_addr, &len);
    if (ret < 0) {
        std::cerr << "Receive failed" << std::endl;
        return 1;
    }

    std::cout << "Message from server: " << buffer << std::endl;

    close(fd);
    return 0;
}
